﻿using System;
using System.Diagnostics;
using System.ServiceModel;
using System.Threading;

namespace Hydra.Core
{
    internal class Stethoscope : IStethoscope, IHydraCallback
    {
        private ServiceHost _host;

        public void Start(int pid)
        {
            if (_host == null)
            {
                IHydraService service = new HydraService();
                var address = new Uri("net.pipe://localhost/");
                _host = new ServiceHost(service, address);
                _host.AddServiceEndpoint(typeof(IHydraService), 
                    new NetNamedPipeBinding(), Util.GetHash(pid));
            }
            _host.Open();
        }

        public void Stop()
        {
            if (_host != null)
            {
                _host.Close();
                ((IDisposable)_host).Dispose();
                _host = null;
            }
        }

        public void ApplyDetours(byte[] assembly)
        {
            if (_host != null)
            {
                ((IHydraCallback)_host.SingletonInstance).ApplyDetours(assembly);
            }
        }

        public void ReleaseDetours()
        {
            if (_host != null)
            {
                ((IHydraCallback)_host.SingletonInstance).ReleaseDetours();
            }
        }
    }
}